#
# Retrieve m random elements from a two-dimensional source array
# of length n, whose terminal elements are of length 4
# 
# Author: Kyle Taylor (kyle.a.taylor@gmail.com)
# 2012
#

import sys, os
import random

def getRandomElements(retNumElements, sourceArray):

  # ensure that we even have enough elements to retrieve the requested amount

  if retNumElements > len(sourceArray):
    return 0

  # array to hold a running record of the numbers previously generated
  numbersUsed = [-1 for col in range(retNumElements)]
  
  # initialize a sample array of length retNumElements to hold the data we are going to return
  sampleArray = [[0 for x in xrange(4)] for x in range(retNumElements)] 

  # Dimension our sampleArray and fill it with zeros so we don't have to append
  # new values.  This can save a lot of time when working with very large sample sets.

  for h in range(retNumElements): 
    sampleArray[h][0] = 0
    sampleArray[h][1] = 0
    sampleArray[h][2] = "null"
    sampleArray[h][3] = "null"

  for i in range(retNumElements):
  
    # generate a random number to pull out of our sourceArray
    samplePos = random.randint(0,len(sourceArray)-1) # prime the pump for a position

    # make sure the samplePos we generated hasn't already been used.  We want unique values.

    for x in xrange(len(numbersUsed)):
      if samplePos == numbersUsed[x]:
        samplePos = random.randint(0,len(sourceArray)-1)
        x = 0
    
    numbersUsed[i] = samplePos
    
    # retrieve values at the randomized position to the sample array we are going to return

    sampleArray[i][0] = sourceArray[samplePos][0] # X element
    sampleArray[i][1] = sourceArray[samplePos][1] # Y element
    sampleArray[i][2] = sourceArray[samplePos][2] # Field value (Ear_Tag)
    sampleArray[i][3] = sourceArray[samplePos][3] # Field value (Research_Y)

  return sampleArray
